import React, {Component} from 'react';
import {FlatList, View} from 'react-native';
import {globalStore} from "../../libs/ShareStore";
import {listViewStyle} from "./style/listViewStyle";
import RoomListData from "../../model/item/RoomListData";
import RoomListItem from "./item/RoomListItem";
import {RoomListStore} from "../../model/store/RoomListStore";
import Beans from "../../libs/sdk/echatim/common/utils";


type RoomListStateType = {
    items:Array<RoomListData>,
    refreshing:boolean,
}

export default class RoomListView extends Component<any, RoomListStateType> {
    constructor(props) {
        super(props);

        this.state = {
            items:new Array<RoomListData>(),
            refreshing: false
        };
        globalStore.addRoomListener(this.onRoomUpdate.bind(this));
    }

    componentDidMount(): void {
        this.onRoomUpdate(globalStore.roomList);
    }


    onRoomUpdate(rooms:Array<RoomListStore>):void{
        console.log(`onRoomUpdate:${Beans.json(rooms)}`);
        this.setState( {
            items:rooms.map((v)=>{
                const data =  new RoomListData();
                data.id = v.rid + '';
                data.avatar = v.avatar;
                data.name = v.name;
                data.body = '';
                data.unread = v.unread;
                data.owner = v.owner;
                data.lastMsgTime = v.lastMsgTime;
                data.announce = v.announce;
                data.introduce = v.introduce;

                return data;
            }),
            refreshing: !this.state.refreshing
        });
    }

    render() {
        return (
            <View style = {listViewStyle.container}>
                <View style={listViewStyle.list}>
                    <FlatList
                        extraData = {this.state.refreshing}
                        data = {this.state.items}
                        renderItem = {({item})=><RoomListItem data={item}  avatar={item.avatar}  body={item.body} name={item.name} unread={item.unread} />}
                    />
                </View>
            </View>
        );
    }
}

